package com.itheima.filter;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@jakarta.servlet.annotation.WebFilter(urlPatterns = "/*")
public class WebFilter implements Filter {


//    拦截方法，多次调用
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//      拦截操作
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String url = req.getRequestURL().toString();
        log.info("请求url{}", url);
        String token = req.getHeader("token");

//      放行
        if(url.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else if(!StringUtils.hasLength(token)){

            {
                log.info("请求头为空");
                Result error = Result.error("NOT_LOGIN");
                //阿里的fastjosn，用来转换josn格式,返回未登录结果
                String jsonString = JSONObject.toJSONString(error);
                resp.getWriter().write(jsonString);
            }
        }
        else{
            try{
                JwtUtils.parseJWT(token);
            }
            catch (Exception e){
                e.printStackTrace();
                log.info("解析令牌失败");
                Result error = Result.error("NOT_LOGIN");
                //阿里的fastjosn，用来转换josn格式,返回未登录结果
                String jsonString = JSONObject.toJSONString(error);
                resp.getWriter().write(jsonString);
                return;
            }
            log.info("令牌可用");
            filterChain.doFilter(req, resp);
        }


//      放行后逻辑

    }
}
